<template>
  <div>
    <!-- 1.nav-ber -->
    <van-nav-bar title="黑马头条" />
    <!-- 表单登录 -->
    <van-form @submit="onSubmit" @failed="onFailed">
      <van-field
        v-model.trim="user.mobile"
        name="手机号"
        label="手机号"
        placeholder="手机号"
        :rules="[{ pattern: /^1\d{10}$/, message: '手机号错误' }]"
      />
      <van-field
        v-model.trim="user.code"
        type="password"
        name="验证码"
        label="验证码"
        placeholder="验证码"
        :rules="[{ pattern: /^\d{6}$/, message: '验证码错误' }]"
      />
      <div style="margin: 16px" class="btn-wrap">
        <van-button
          class="van-button"
          block
          type="info"
          native-type="submit"
          @click="doLogin"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// import { login } from '../../api/user'
export default {
  // name可以查看组件名字
  name: 'login',
  data () {
    return {
      user: {
        mobile: '13800000002', // 测试账号可以登录
        code: '246810'
      }
    }
  },
  methods: {
    async doLogin () {
      this.$toast({
        message: '加载中...',
        overlay: true, // 整体增加一个遮罩
        duration: 0 // 持续提示toast，永远不会关闭
      })
      // 做具体的ajax提交
      try {
        await this.$store.dispatch('userLogin', this.user)
        // console.log(res)
        // 调用带命名空间的moudules中的actions
        await this.$store.dispatch('user/getProfile')
        this.$toast.success('登录成功')
        // 只要登录成功跳转到主页
        // 如果有backto就用，没有就跳到主页
        this.$router.push(this.$route.query.backto || '/')
      } catch (err) {
        console.log(err)
        this.$toast.fail('登录失败')
      }
    },
    onSubmit (values) {
      console.log('submit', values)
    },
    onFailed () {
      console.log('验证失败')
    }
  }

}
</script>

<style lang="less" scoped>
// 按钮
.btn-wrap {
  padding: 20px;
  .van-button {
    width: 100%;
    background-color: #6db4fd;
    color: #fff;
  }
}
</style>
